/*
 * Copyright 2019 Flipkart Internet Pvt. Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.flipkart.ohos.proteus.view.custom;

import ohos.agp.colors.RgbPalette;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.Component.DrawTask;
import ohos.agp.components.ComponentTreeObserver;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.utils.Color;
import ohos.app.Context;

import com.flipkart.ohos.proteus.ProteusView;

/**
 * CircleView
 *
 * @author aditya.sharat
 */
public class CircleView extends Component implements ProteusView, DrawTask {
    private Manager viewManager;
    private String hexColor = "#45ba8a";
    private Paint drawPaint;
    private float radius;

    public CircleView(Context context) {
        this(context, null);
    }

    public CircleView(final Context context, final AttrSet attrs) {
        this(context, attrs, "");
    }

    public CircleView(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        init();
        addDrawTask(this);
    }

    public void setColor(String color) {
        this.hexColor = color;
    }

    @Override
    public Manager getViewManager() {
        return viewManager;
    }

    @Override
    public void setViewManager(Manager viewManager) {
        this.viewManager = viewManager;
    }

    private void init() {
        drawPaint = new Paint();
        drawPaint.setColor(new Color(RgbPalette.parse(hexColor)));
        drawPaint.setAntiAlias(true);
        setOnMeasureCallback();
    }

    @Override
    public void onDraw(Component component, Canvas canvas) {
        radius = getEstimatedWidth() >> 1;
        canvas.drawCircle(radius, radius, radius, drawPaint);
    }

    private void setOnMeasureCallback() {
        setLayoutRefreshedListener(component -> radius = getEstimatedWidth() >> 1);
    }

    void removeOnGlobalLayoutListener(ComponentTreeObserver.GlobalFocusUpdatedListener listener) {
        //noinspection deprecation
        getComponentTreeObserver().removeGlobalFocusUpdatedListener(listener);
    }

    @Override
    public Component getAsView() {
        return this;
    }
}
